import router from '@/router'
import store from '@/store'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'
import Layout from '@/layout'
import preview from '@/views/report/preview/index.vue'
import fileView from '@/views/fileManager/fileView/index.vue'
import uploadFileView from '@/views/fileManager/uploadFileView'

NProgress.configure({
  showSpinner: false,
})

const whiteList = ['/login', '/oa'] // no redirect whitelist

export function initPermission(app) {
  router.beforeEach(async (to, from, next) => {
    addReportRouter(app, to)
    addFileViewRouter(to)
    addFlowableRouter(to)
    // start progress bar
    NProgress.start()
    // set page title
    document.title = getPageTitle(to.meta.title)
    // determine whether the user has logged in
    const hasToken = getToken()
    if (to.path === '/appDownload' || to.apth === '/pendCheckChargingProduct') {
      //打开app下载页面时不做拦截
      next()
    } else if (to.path === '/callback' && to.query?.code) {
      // 三方登录
      next()
    } else {
      if (hasToken) {
        if (to.path === '/login') {
          next()
          NProgress.done()
        } else {
          const hasRoles =
            store.state.permission.addRoutes &&
            store.state.permission.addRoutes.length > 0
          if (hasRoles) {
            next()
          } else {
            try {
              // generate accessible routes map based on roles
              const accessRoutes = await store.dispatch(
                'permission/generateRoutes'
              )
              await store.dispatch('permission/getUserPermissionCodes')
              // dynamically add accessible routes
              accessRoutes.forEach((route) => {
                router.addRoute(route)
              })
              // hack method to ensure that addRoutes is complete
              // set the replace: true, so the navigation will not leave a history record
              next({
                ...to,
                replace: true,
              })
            } catch (error) {
              // remove token and go to login page to re-login
              await store.dispatch('user/resetToken')
              ElMessage.error(error || 'Has Error')
              next(`/login?redirect=${to.path}`)
              NProgress.done()
            }
          }
        }
      } else {
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
          // in the free login whitelist, go directly
          next()
        } else {
          // other pages that do not have permission to access are redirected to the login page.
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  })

  router.afterEach(() => {
    // finish progress bar
    sessionStorage.removeItem('storeRowId')
    NProgress.done()
  })
}

function isChinese(s) {
  let reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
  if (reg.test(s)) {
    return true
  } else {
    return false
  }
}
// 添加动态路由--报表菜单多开路由(缓存动态路由并且是ifream菜单)
function addReportRouter(app, to) {
  const path = to.fullPath
  const name = to.params.name
  const has_u = to.fullPath.includes('_u')
  if (to.fullPath.includes('/report/preview/') && has_u) {
    let iframeName = store.state.template.iframeName
    to.name = name
    iframeName.push(name)
    app.component(name, preview)
    store.commit('SET_IFRAMENAME', [...new Set(iframeName)])
    router.addRoute({
      name: name,
      path: '/report/preview',
      component: Layout,
      meta: {
        title: '报表预览',
      },
      children: [
        {
          path: to.fullPath,
          name: name,
          component: preview,
          meta: { title: '报表预览' },
        },
      ],
    })
    // 设置自定义报表tab名称
    if (isChinese(decodeURIComponent(path))) {
      to.meta.title = name
    }
  } else if (to.fullPath.includes('/report/preview') && has_u) {
    const name = to.query._u.split('slip-')[1].split('.ureport.xml')[0]
    let currentRouter = router.getRoutes().find((element) => {
      return element.meta.title === name
    })
    if (currentRouter && currentRouter !== -1) {
      router.replace(currentRouter.path)
    }
    // 设置报表tab名称
    if (isChinese(decodeURIComponent(path))) {
      let title = '报表预览',
        perfix = 'slip-',
        reprotSuffix = '.ureport.xml',
        _u = to.query._u
      if (_u) {
        if (_u.includes(perfix)) {
          title = decodeURIComponent(_u.split(perfix)[1].split(reprotSuffix)[0])
        } else {
          title = decodeURIComponent(_u.split(reprotSuffix)[0])
        }
      }
      if (isChinese(title)) {
        to.meta.title = title
      }
    }
  }
}
// 添加文档预览
function addFileViewRouter(to) {
  const name = 'fileView' + new Date().getTime()
  if (to.fullPath.includes('/fileManager/fileview/')) {
    const path = to.fullPath
    to.name = name
    router.addRoute({
      path: '/fileManager/fileview',
      component: Layout,
      children: [
        {
          path,
          name,
          component: fileView,
          meta: { title: '文档预览' },
        },
      ],
    })
  }
  if (to.fullPath.includes('/fileManager/uploadFileView/')) {
    const path = to.fullPath
    to.name = name
    router.addRoute({
      path: '/fileManager/uploadFileView',
      component: Layout,
      children: [
        {
          path,
          name,
          component: uploadFileView,
          meta: { title: '文档详情' },
        },
      ],
    })
  }
}
function addFlowableRouter(to) {
  if (to.fullPath.indexOf('/task/myFinishedDetails/') !== -1) {
    const name = to.params.name // 设置自定义报表tab名称
    to.meta.title = name + '-已办'
  } else if (to.fullPath.indexOf('/task/myPendingDetails/') !== -1) {
    const name = to.params.name // 设置自定义报表tab名称
    to.meta.title = name + '-待办'
  }
}
